package com.yuexiang.melodyhub.authserver.handler;

import com.yuexiang.melodyhub.authserver.feign.UserFeignService;
import com.yuexiang.melodyhub.authserver.handler.context.LoginContext;
import com.yuexiang.melodyhub.common.constant.UsualConstant.BizConstant;
import com.yuexiang.melodyhub.common.dto.user.UserFindWithRolesByUsername.response.UserFindWithRolesByUsernameResponse;
import com.yuexiang.melodyhub.common.dto.user.UserFindWithRolesByUsername.response.data.RoleData;
import com.yuexiang.melodyhub.common.exception.gateway.UnavailableServiceException;
import com.yuexiang.melodyhub.common.handler.AbstractValidationHandler;
import com.yuexiang.melodyhub.common.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class TokenGenerationHandler extends AbstractValidationHandler<LoginContext> {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserFeignService userFeignService;

    @Override
    public void handler(LoginContext content) {
        UserFindWithRolesByUsernameResponse userFindResponse = content.getUserFindResponse();
        try {
            userFeignService.saveLastTimeByEmail(userFindResponse.getEmail());
        } catch (Exception e) {
            throw new UnavailableServiceException();
        }
        String token = JwtUtil.generateToken(userFindResponse.getUsername(), userFindResponse.getRoles().stream().map(RoleData::getRoleName).collect(Collectors.toList()));
        redisTemplate.opsForValue().set(BizConstant.TOKEN_CACHE_PREFIX + userFindResponse.getUsername(), token, BizConstant.TOKEN_CACHE_EXPIRE_HOURS, TimeUnit.HOURS);
        content.setEmail(userFindResponse.getEmail());
        content.setAvatar(userFindResponse.getAvatar());
        content.setToken(token);
        handlerNext(content);
    }
}
